package com.xgq.drink.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xgq.drink.annotation.RequiresRole;
import com.xgq.drink.entity.UserRole;
import com.xgq.drink.mapper.UserRoleMapper;
import com.xgq.drink.service.IUserService;
import com.xgq.drink.utils.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class RoleCheckAspect {
    
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Around("@annotation(com.xgq.drink.annotation.RequiresRole)")
    public Object checkRole(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }

        // 获取用户ID
        Long userId = Long.parseLong(authentication.getName());
        
        // 获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RequiresRole requiresRole = signature.getMethod().getAnnotation(RequiresRole.class);
        String[] requiredRoles = requiresRole.value();
        boolean brandRequired = requiresRole.brandRequired();
        System.out.println("----------------------");
        System.out.println("brandRequired: " + brandRequired);
        System.out.println("requiredRoles: " + String.join(", ", requiredRoles));
        // 检查角色
        if (brandRequired) {
            // 从请求头获取token
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String token = request.getHeader("Authorization");

            // 从token解析店铺ID
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            System.out.println("解析到的店铺ID: " + brandId);

            if (brandId == null) {
                throw new RuntimeException("Token中缺少店铺信息");
            }
            if (brandId==0){
                System.out.println("管理员登录");
                QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",userId);
                queryWrapper.eq("role_id",2);
                if (userRoleMapper.selectCount(queryWrapper)>0){
                    return joinPoint.proceed();
                }else {
                    throw new RuntimeException("用户没有所需的角色权限");
                }
            }
            // 检查是否拥有任一所需角色（后续代码保持不变）
            boolean hasAnyRole = false;
            for (String role : requiredRoles) {
                if (userService.hasBrandRole(userId, brandId, role)) {
                    hasAnyRole = true;
                    break;
                }
            }
            if (!hasAnyRole) {
                throw new RuntimeException("用户没有所需的角色权限");
            }
        } else {
            // 检查是否拥有任一所需角色
            boolean hasAnyRole = false;
            for (String role : requiredRoles) {
                if (userService.hasRole(userId, role)) {
                    hasAnyRole = true;
                    break;
                }
            }
            if (!hasAnyRole) {
                throw new RuntimeException("用户没有所需的角色权限");
            }
        }

        return joinPoint.proceed();
    }
}
